#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
PDF导出模块
"""

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import reportlab.lib.fonts
import os
import sys
# 导入布局保持模块
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../')
from layout_preserver import LayoutPreserver

class PDFExporter:
    def __init__(self):
        # 注册中文字体
        self._register_chinese_fonts()
        # 初始化布局保持器
        self.layout_preserver = LayoutPreserver()
    
    def _register_chinese_fonts(self):
        """注册中文字体"""
        try:
            # 尝试注册常见的中文字体
            # Windows系统字体路径
            font_paths = [
                "C:/Windows/Fonts/msyh.ttc",      # 微软雅黑
                "C:/Windows/Fonts/simsun.ttc",    # 宋体
                "C:/Windows/Fonts/simhei.ttf",    # 黑体
                "/System/Library/Fonts/PingFang.ttc",  # macOS字体
                "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",  # Linux字体
            ]
            
            font_registered = False
            for font_path in font_paths:
                if os.path.exists(font_path):
                    # 注册字体
                    pdfmetrics.registerFont(TTFont('ChineseFont', font_path))
                    font_registered = True
                    break
            
            # 如果没有找到系统字体，使用默认字体
            if not font_registered:
                # 尝试注册系统中的其他字体
                if sys.platform.startswith('win'):
                    font_path = "C:/Windows/Fonts/arialuni.ttf"
                    if os.path.exists(font_path):
                        pdfmetrics.registerFont(TTFont('ChineseFont', font_path))
                    else:
                        # 使用默认字体
                        pass
                elif sys.platform.startswith('darwin'):  # macOS
                    font_path = "/System/Library/Fonts/Arial Unicode.ttf"
                    if os.path.exists(font_path):
                        pdfmetrics.registerFont(TTFont('ChineseFont', font_path))
                else:  # Linux
                    # 在Linux系统上尝试常见的中文字体
                    chinese_fonts = [
                        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
                        "/usr/share/fonts/truetype/arphic/uming.ttc",
                        "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
                    ]
                    for font_path in chinese_fonts:
                        if os.path.exists(font_path):
                            pdfmetrics.registerFont(TTFont('ChineseFont', font_path))
                            break
        except Exception as e:
            print(f"字体注册失败: {e}")
            # 如果字体注册失败，继续使用默认字体
    
    def export_text_to_pdf(self, file_path, text, page_size=A4):
        """
        将文本导出为PDF文件
        
        Args:
            file_path (str): 输出PDF文件路径
            text (str): 要导出的文本内容
            page_size: 页面大小，默认A4
        """
        c = canvas.Canvas(file_path, pagesize=page_size)
        width, height = page_size
        
        # 设置中文字体，如果注册失败则使用默认字体
        try:
            c.setFont("ChineseFont", 12)
        except:
            # 如果中文字体不可用，使用Helvetica-Bold作为备选
            c.setFont("Helvetica-Bold", 12)
        
        # 处理文本换行
        lines = text.split('\n')
        y_position = height - 50
        
        for line in lines:
            # 如果到达页面底部，创建新页面
            if y_position < 50:
                c.showPage()
                try:
                    c.setFont("ChineseFont", 12)
                except:
                    c.setFont("Helvetica-Bold", 12)
                y_position = height - 50
            
            # 绘制文本
            try:
                c.drawString(50, y_position, line)
            except:
                # 如果当前字体无法显示某些字符，尝试使用其他方式
                try:
                    # 尝试使用不同的编码方式绘制文本
                    c.drawString(50, y_position, line.encode('utf-8').decode('utf-8'))
                except:
                    # 最后尝试，只绘制可安全编码的字符
                    safe_line = ''.join([char if ord(char) < 128 else '?' for char in line])
                    c.drawString(50, y_position, safe_line)
            
            y_position -= 15
        
        c.save()
    
    def export_layout_preserved_pdf(self, file_path, all_page_results, page_size=A4):
        """
        将多页OCR结果按原样排版导出为PDF文件
        
        Args:
            file_path (str): 输出PDF文件路径
            all_page_results (dict): 所有页面的OCR结果，key为页面路径，value为结果列表
            page_size: 页面大小，默认A4
        """
        c = canvas.Canvas(file_path, pagesize=page_size)
        width, height = page_size
        
        # 设置中文字体
        try:
            c.setFont("ChineseFont", 12)
        except:
            c.setFont("Helvetica-Bold", 12)
        
        # 按页面处理
        for i, (page_path, page_results) in enumerate(all_page_results.items()):
            # 如果不是第一页，创建新页面
            if i > 0:
                c.showPage()
                try:
                    c.setFont("ChineseFont", 12)
                except:
                    c.setFont("Helvetica-Bold", 12)
            
            # 获取当前页面的坐标范围以确定缩放比例
            if page_results:
                max_x = max([result["coordinates"][2] for result in page_results]) if page_results else width
                max_y = max([result["coordinates"][3] for result in page_results]) if page_results else height
                
                # 计算缩放比例
                scale_x = width / max_x if max_x > 0 else 1
                scale_y = height / max_y if max_y > 0 else 1
                scale = min(scale_x, scale_y, 1.0)  # 不放大，只缩小
                
                # 按坐标绘制文本
                for result in page_results:
                    if isinstance(result, dict) and "text" in result and "coordinates" in result:
                        text = result["text"]
                        coords = result["coordinates"]
                        
                        # 坐标转换（PDF坐标系与图像坐标系可能不同）
                        x = coords[0] * scale if len(coords) > 0 else 50
                        y = height - (coords[1] * scale) if len(coords) > 1 else height - 50  # 翻转Y轴
                        
                        # 确保坐标在页面范围内
                        x = max(10, min(x, width - 10))
                        y = max(10, min(y, height - 10))
                        
                        # 绘制文本
                        try:
                            c.drawString(x, y, text)
                        except:
                            try:
                                c.drawString(x, y, text.encode('utf-8').decode('utf-8'))
                            except:
                                safe_text = ''.join([char if ord(char) < 128 else '?' for char in text])
                                c.drawString(x, y, safe_text)
        
        c.save()